<template >
  <div>
    <div v-if="field.label">
      <q-icon name="stars" size="sm" color="grey-9" class="q-mr-sm" />
      <span class="text-body1 text-bold">{{ field.label }}</span>

      <q-separator class="q-mt-sm q-mb-md" />
    </div>

    <div v-html="sanitizeHtml" ref="termsContent"></div>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import DOMPurify from 'dompurify';

export default defineComponent({
  name: 'additinalTerms',
  props: {
    field: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      // 需要取赋值的tag，注意，需要有name
      tags: ['input', 'textarea']
    }
  },
  methods: {
    serializeVal () { // 序列化各输入框的值
      const values = {};
      for (const tag of this.tags) {
        const nodes = this.$refs.termsContent.getElementsByTagName(tag);
        for (const node of nodes) {
          if (node.name) {
            values[node.name] = node.value;
          }
        }
      }
      return values;
    },
    parseVal (values) { // 填空
      for (const tag of this.tags) {
        const nodes = this.$refs.termsContent.getElementsByTagName(tag);
        for (const node of nodes) {
          if (node.name && values && values[node.name] !== undefined) {
            node.value = values[node.name] || '';
          }
        }
      }
    },
    bindChangeEvent () { // 为条款里的input及textarea绑定change事件
      const inputs = this.$refs.termsContent.querySelectorAll('input');
      inputs.forEach(input => {
        input.addEventListener('change', this.handleChange);
      });

      const textareas = this.$refs.termsContent.querySelectorAll('textarea');
      textareas.forEach(textarea => {
        textarea.addEventListener('change', this.handleChange);
      });
    },
    handleChange (event) {
      this.field.value = this.serializeVal();
    }
  },
  computed: {
    sanitizeHtml () {
      return DOMPurify.sanitize(this.field.terms);
    }
  },
  watch: {
    'field.value' (val) {
      this.parseVal(val);
    },
    'field.terms' () {
      this.$nextTick(() => {
        this.bindChangeEvent();
        if (this.field.value) {
          this.parseVal(this.field.value);
        } else {
          this.field.value = this.serializeVal();
        }
      });
    }
  }
});

</script>
